/* $RCSFile: DocumentsEdit.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/Documents/DocumentsEdit.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:52  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Helpers;
using AddonNice.Security;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Settings.PageModules.Documents;

using Trace2    =   System.Diagnostics.Trace;
using AddonNice.CRMWrapper;

namespace AddonNice.PageModules.Documents
{
    /// <summary>
    /// Update and edit documents.
    /// </summary>
	public partial class DocumentsEdit : AddEditItemPage
    {

		string PathToSave		=	string.Empty;
		DocumentDB documents	=   new DocumentDB();

        public DocumentsEdit() : base(true, true, true, true)
        {}

        /// <summary>
        /// The Page_Load event on this Page is used to obtain the ModuleID
        /// and ItemID of the document to edit.
        /// It then uses the DocumentDB() data component
        /// to populate the page's edit controls with the document details.
        /// </summary>
        protected void Page_Load(object sender, System.EventArgs e) 
        {
            // If the page is being requested the first time, determine if an
            // document itemID value is specified, and if so populate page
            // contents with the document details
            if (!IsPostBack) 
            {
                if ( ModuleID > 0)
                    PathToSave                      =   moduleSettingsDic[DStr.DOCUMENTS_PATH].FullPath;

				if ( !isNewItem ) 
				{
					// Obtain a single row of document information
					SqlDataReader dr                =   null;
					try
					{
                        if ( !isCrmItem )
                        {
                            dr                      =   documents.GetSingleDocumentGlobalized(ItemID);

                            // Load first row into Datareader
                            if ( dr.Read() )
                            {

                                NameField.Text      =   (string)dr["FileFriendlyName"];
                                PathField.Text      =   (string)dr["FileNameUrl"];
                                CategoryField.Text  =   (string)dr["Category"];
                                CreatedBy.Text      =   (string)dr["CreatedByUser"];
                                CreatedDate.Text    =   ( (DateTime)dr["CreatedDate"] ).ToShortDateString();
                                if ( CreatedBy.Text == StStr.unknown )
                                {
                                    CreatedBy.Text  =   LocalizeHelper.Localize(StStr.UNKNOWN,StStr.unknown);
                                }
                            }
                        }
                        else
                        {
                            ADNDynSalesliteratureitem s =   new ADNDynSalesliteratureitem(Wrapper,ItemCrmID);
                            s.Retrieve();
                            NameField.Text          =   s.title;
                            PathField.Text          =   s.attacheddocumenturl;
                            CategoryField.Text      =   s.filetypecodeLabel;
                            CategoryField.Enabled   =   false;
                            CreatedBy.Text          =   s.authorname;
                            CreatedDate.Text        =   s.createdon;
                        }
					}
					catch(Exception ex)
					{
						if (PageTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentsEdit Page_Load  ex : {0}",ex),PageTraceSwitch.Sw.Info);
                        throw;
					}
					finally
					{
						if ( dr != null )
							dr.Close();
					}
				}
				else
				{
					CreatedBy.Text		        =   PortalSecurity.Wrapper.userName;
					CreatedDate.Text	        =   DateTime.Now.ToShortDateString();
				}

            }
        }

		/// <summary>
		/// Set the module guids with free access to this page
		/// </summary>
		protected override ArrayList AllowedModules
		{
			get
			{
				ArrayList al = new ArrayList();
				al.Add ("F9645B82-CB45-4C4C-BB2D-72FA42FE2B75");
				return al;
			}
		}

		/// <summary>
        /// create or update an document.  It  uses the DocumentDB()
        /// data component to encapsulate all data functionality.
        /// </summary>
        void DocumentsEdit_Update(object sender, AddonNice.UI.ADNPageEventArgs e)
        {
            bool updateFile                 =   (FileUpload.PostedFile.FileName != string.Empty);
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DocumentsEdit DocumentsEdit_Update BEG updateFile: {0}, isCrmItem: {1}",
                    updateFile,isCrmItem),PageTraceSwitch.Sw.Info);
			byte [] buffer                  =   new byte[0];
			int size                        =   0;

            // Determine whether a file was uploaded
            if (FileUpload.PostedFile.FileName != string.Empty) 
            {
				FileInfo fInfo				=	new FileInfo(FileUpload.PostedFile.FileName);
                // Save only in DB or save in CRM
				if ( isCrmItem || moduleSettingsDic[DStr.DOCUMENTS_DBSAVE].ToBool() ) 
				{
					System.IO.Stream stream =	FileUpload.PostedFile.InputStream;
					size					=	FileUpload.PostedFile.ContentLength;
					buffer					=	new byte[size];
					try
					{
						stream.Read(buffer, 0, size);
						PathField.Text		=   fInfo.Name;
					}
					catch(Exception ex)
					{
						if (PageTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentsEdit DocumentsEdit_Update ex : {0}",ex),PageTraceSwitch.Sw.Info);
                        e.Cancel            =   true;
					}
					finally
					{
						stream.Close();
					}
				} 
				else 
				{
                    bool useDefFolder       =   moduleSettingsDic[DStr.DOCUMENTS_USE_DEFAULT].ToBool();
                    if ( useDefFolder )
                            PathToSave	    =	portalSettings.DefaultDocumentVirtualPath;
					else    PathToSave		=	moduleSettingsDic[DStr.DOCUMENTS_PATH].FullPath;
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DocumentsEdit DocumentsEdit_Update PathToSave: {0}",PathToSave),PageTraceSwitch.Sw.Info);
					if (!System.IO.Directory.Exists(Server.MapPath(PathToSave)))
						System.IO.Directory.CreateDirectory(Server.MapPath(PathToSave));
		
					string virtualPath		=	AddonNice.Settings.Path.WebPathCombine(PathToSave, fInfo.Name);
					string physicalPath		=	Server.MapPath(virtualPath);
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DocumentsEdit DocumentsEdit_Update physicalPath: {0}",physicalPath),PageTraceSwitch.Sw.Info);
					// Delete file before upload
					while(File.Exists(physicalPath))
					{
						try
						{
							File.Delete(physicalPath);
						}
						catch(Exception ex)
						{
							if (PageTraceSwitch.Sw.TraceError)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentsEdit DocumentsEdit_Update Deleting: {0}, ex: {1}",physicalPath,ex),PageTraceSwitch.Sw.Info);
                            Message.Text    =   LocalizeHelper.Localize(DStr.ERROR_FILE_DELETE, "Error while deleting file!<br>");
                            e.Cancel        =   true;
							return;             
						}
					}


					try
					{
						// Save file to uploads directory
						FileUpload.PostedFile.SaveAs(physicalPath);
						// Update PathFile with uploaded virtual file location
                        if ( useDefFolder )
                             PathField.Text =	fInfo.Name;
						else PathField.Text	=	virtualPath;
					}
					catch(Exception ex)
					{
						Message.Text		=	LocalizeHelper.Localize (DStr.ERROR_FILE_NAME, "Invalid file name!<br>") +  ex.Message;
                        e.Cancel            =   true;
						return;                      
					}
				}
			}
			try
			{
                if ( !isCrmItem )
                {
                    string contentType	    =	PathField.Text.Substring(PathField.Text.LastIndexOf(".") + 1).ToLower();
                    documents.UpdateDocumentGlobalized(ModuleID,ItemID,PortalSecurity.Wrapper.userName,NameField.Text,PathField.Text,CategoryField.Text,buffer,size,contentType);
                }
                else
                {
                    ADNDynSalesliteratureitem s =   new ADNDynSalesliteratureitem(Wrapper,ItemCrmID);
                    s.Retrieve();
                    s.title                 =   NameField.Text;
                    s.authorname            =   CreatedBy.Text;
                    if ( updateFile )
                        s.documentbody      =   System.Convert.ToBase64String(buffer);
                    s.Update();
                }
			}
			catch(Exception ex)
			{
				if (PageTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentsEdit DocumentsEdit_Update ex: {0}",ex),PageTraceSwitch.Sw.Info);
				throw;
			}
        }
    
        /// <summary>
        /// Delete a document.  It  uses the AddonNice.DocumentsDB()
        /// data component to encapsulate all data functionality.
        /// </summary>
        void DocumentsEdit_Delete(object sender, AddonNice.UI.ADNPageEventArgs e)
        {

			// Only attempt to delete the item if it is an existing item
            if ( !isNewItem ) 
            {
				try
				{
					documents.DeleteDocumentGlobalized(ItemID, Server.MapPath(PathField.Text));
				}
				catch(Exception ex)
				{
					if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DocumentsEdit OnDelete  ex : {0}",ex),PageTraceSwitch.Sw.Info);
					throw;
				}
			}
        }
        
		#region Std Overrides
        
        /// <summary>
        /// Here we create the command buttons and add them to the PlaceHolders prepared
        /// </summary>
        override protected void OnPreInit(EventArgs e)
        {
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]DocumentsEdit OnPreInit BEG.",PageTraceSwitch.Sw.Info);
            if ( isNewItem ) 
                PageHasDeleteBtn    =   false;
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DocumentsEdit OnPreInit PageHasDeleteBtn: {0}.",PageHasDeleteBtn),PageTraceSwitch.Sw.Info);
            base.OnPreInit(e);
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]DocumentsEdit OnPreInit END.",PageTraceSwitch.Sw.Info);
        }

        /// <summary>
        /// Raises OnInitEvent
        /// </summary>
        /// <param name="e"></param>
        override protected void OnInit(EventArgs e)
        {
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]DocumentsEdit Init BEG.",PageTraceSwitch.Sw.Info);
            InitializeComponent();

            //Translate
            CreatedLabel.Text           =   LocalizeHelper.Localize(DStr.CREATED_BY,"Created By"); 
            OnLabel.Text		        =   LocalizeHelper.Localize(DStr.ON,"On");
            PageTitleLabel.Text         =   LocalizeHelper.Localize(DStr.DOCUMENT_DETAILS,"Document details");
            FileNameLabel.Text	        =   LocalizeHelper.Localize(DStr.FILE_NAME,"File Name");
            CategoryLabel.Text	        =   LocalizeHelper.Localize(DStr.CATEGORY,"Category");
            UrlLabel.Text		        =   LocalizeHelper.Localize(DStr.URL,"Url");
            UploadLabel.Text	        =   LocalizeHelper.Localize(DStr.UPLOAD_FILE,"Upload File");
            OrLabel.Text                =   "---" + LocalizeHelper.Localize(DStr.OR,"Or") + "---";

            RequiredFieldValidator1.Text =  LocalizeHelper.Localize(DStr.VALID_FILE_NAME,"Valid File name");
		
            base.OnInit(e);
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]DocumentsEdit Init End",PageTraceSwitch.Sw.Info);
        }

        private void InitializeComponent() 
        {
			Load	        +=      new EventHandler(Page_Load);
            Update          +=      new PageEventHandler(DocumentsEdit_Update);
            Delete          +=      new PageEventHandler(DocumentsEdit_Delete);
		}

        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons
		{
			get
			{ return PlaceHolderButtons; }
			set { }
		}

        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons2
		{
			get
			{ return PlaceHolderButtons2; }
			set { }
		}

        #endregion

    }
}
